<template>
  <u-table-column
    v-if="column.isShow && isPlatformShow && !noShowKeys.includes(column.fieldName)"
    :key="column.fieldName"
    :min-width="propsData.minWidth || '110px'"
    v-bind="propsData || {}"
    class-name="edit-column"
  >
    <!-- <template slot="header" slot-scope="scope">
      <div :title="scope.column.label" class="ellipsisOne">{{ scope.column.label }}</div>
    </template> -->
    <template slot-scope="scope">
      <i v-if="fieldEditAuth(column,scope)" class="edit-info" @click="editModule(scope.row, column.editModule)" />
      <ToolTip
        v-if="dataInfoKey.includes(column.fieldName)"
        :content="getData(scope.row) | bigNumFilter"
        :tool-tip="getData(scope.row) | moneyFilter" />
      <ToolTip v-else-if="textkey.includes(column.fieldName)" :content="getData(scope.row)"/>
      <div v-else-if="dateKey.includes(column.fieldName)">{{ scope.row[propsData.parentField][column.fieldName] | format(propsData.format || 'YYYY/MM/DD HH:mm') }}</div>
      <ToolTip
        v-else-if="['cooperation'].includes(column.fieldName)"
        :content="getData(scope.row)"
        is-can-click
        @handelClick="toCooperation(scope.row)"/>
      <ToolTip
        v-else-if="['attributionMatrixName'].includes(column.fieldName)"
        :tool-tip="(scope.row.attributionMatrixFullName || scope.row.attributionMatrixName) | getDeptFullName"
        :content="getData(scope.row)"/>
      <div v-else-if="column.fieldName === 'supplierType'">{{ scope.row.supplierType | getSupplierType }}</div>
      <div v-else-if="['status', 'microTask'].includes(column.fieldName)">{{ scope.row[column.fieldName] ? '是' : '否' }}</div>
      <!-- 字段合集 -->
      <div v-else-if="collectionKey.includes(column.fieldName)">
        <i v-if="hasCollectionEditAuth(scope.row, column.fieldName)" class="edit-info" @click="editInfo(scope.row)" />
        <FieldCollection
          :column="column"
          :platform="scope.row.platformId"
          :scope="scope"/>
      </div>

      <template v-else-if="column.fieldName === 'orderNum'">
        <div v-if="scope.row.orderNum" class="cursor-pointer" @click.stop="showOrderDialog(scope.row)">
          {{ scope.row.orderNum }}
        </div>
        <div v-else >--</div>
      </template>
      <StatusText
        v-else-if="['autoPick'].includes(column.fieldName)"
        :color="scope.row.autoPick?'#31CC9C':'#406EFF'"
        :text="scope.row.autoPick ? '已开启' : '未开启'" />
      <!-- 备注 -->
      <template v-else-if="column.fieldName === 'remarks'">
        <div v-if="hasRouteAuth('medium:dataShow:remarks')" class="medium-expand-item">
          <i v-if="hasEditAuth('remarks', scope.row)" class="edit-info" @click="editRemarkMaskShow(scope.row)" />
          <div class="medium-data-remarks">
            <ToolTip
              v-if="scope.row.remarks && scope.row.remarks.content && scope.row.remarks.content.length"
              :content="scope.row.remarks.content" />
            <span v-else>--</span>
          </div>
        </div>
        <div v-else>--</div>
      </template>
      <!-- 案例 -->
      <template v-else-if="column.fieldName === 'cases'">
        <div v-if="hasRouteAuth('medium:dataShow:cases')" class="medium-expand-item">
          <i v-if="hasEditAuth('cases', scope.row)" class="edit-info" @click="editCaseMaskShow(scope.row)" />
          <caseColumn v-if="scope.row.cases" :active-tabs="platform" :data="scope.row.cases" />
        </div>
        <div v-else>--</div>
      </template>
      <template v-else-if="column.fieldName === 'publicationMonth'">
        <ToolTip
          v-if="scope.row.additionalKey && scope.row.additionalKey.publicationMonth"
          :content="scope.row.additionalKey.publicationMonth | format('YYYY/MM')" />
        <div v-else>--</div>
      </template>
      <template v-else-if="additionalKeys.includes(column.fieldName)">
        <template v-if="scope.row.additionalKey">
          <!-- 是否露脸 -->
          <template v-if="['isFrameOut'].includes(column.fieldName)">
            {{ scope.row['additionalKey'][column.fieldName] ? '是' : [false, 0].includes(scope.row['additionalKey'][column.fieldName]) ? '否' : '--' }}
          </template>
          <!-- 是否口播 -->
          <template v-else-if="column.fieldName === 'isVoiceAnchor'">
            {{ scope.row['additionalKey'][column.fieldName] | voiceAnchorFilter }}
          </template>
          <!-- 推荐优先级 -->
          <template v-else-if="column.fieldName === 'recommendRank'">
            {{ scope.row['additionalKey'][column.fieldName] | recommendRankFilter }}
          </template>
          <!-- 含有备注的 -->
          <template v-else-if="['freeAuth', 'otherFreePlatform', 'hasShopPrice', 'retentionAllowed', 'addBrand', 'allowCar', 'carCommission'].includes(column.fieldName)">
            <div style="display: flex; flex-direction: column">
              <div>{{ typeof scope.row['additionalKey'][column.fieldName].isConfirm === 'boolean' ? scope.row['additionalKey'][column.fieldName].isConfirm ? '是' : '否' : '--' }}</div>
              <div class="flex-center">
                <span style="color: #999;">备注：</span>
                <ToolTip :content="scope.row['additionalKey'][column.fieldName].cost || scope.row['additionalKey'][column.fieldName].timeLimit" style="max-width: calc(100% - 45px)"/>
              </div>
            </div>
          </template>
        </template>
        <div v-else>--</div>
      </template>
      <ToolTip
        v-else-if="column.isDynamicKey"
        :content="getDynamicKeyContent(scope.row, column)" />
    </template>
  </u-table-column>
</template>
<script>
import { hasRouteAuth } from '@/utils/permission';
// components
import FieldCollection from './fieldCollection';
import caseColumn from '../caseColumn';
// data
import { tableFieldProps } from '@/views/resource/mixins/listSettingData.js';
// filters
import { moneyFilter } from '@/filters/number';
import { getDeptFullName } from '@/filters/dept';
import { getSupplierType, signStatusFilter } from '@/filters/status';
import { voiceAnchorFilter, recommendRankFilter } from '@/utils/const/resouce';
import { format } from '@/filters/date';

import { mapState } from 'vuex';
export default {
  components: { FieldCollection, caseColumn },
  filters: {
    bigNumFilter(num) {
      let formatNum = Number(num);
      if (formatNum && !Number.isNaN(formatNum)) {
        const isNegative = formatNum < 0 ? '-' : '';
        formatNum = Math.abs(formatNum);
        if (formatNum >= 10000 && formatNum < 100000000) {
          formatNum = moneyFilter(formatNum / 10000) + '万';
        } else if (formatNum >= 100000000) {
          formatNum = moneyFilter(formatNum / 100000000) + '亿';
        }
        return isNegative + formatNum;
      } else {
        return num;
      }
    },
    moneyFilter, getDeptFullName, getSupplierType, signStatusFilter, format,
    voiceAnchorFilter, recommendRankFilter
  },
  props: {
    column: {
      type: Object,
      default: () => {
        return {};
      }
    },
    // 平台，1:微信 2: 微博 3:小红书 4.抖音 5:更多  6:直播 7:B站
    platform: {
      type: String | Number,
      default: ''
    }
  },
  data() {
    return {
      dataInfoKey: [
        'collection', 'averageReadNum', 'exposure', 'averageInteractionNum',
        'averagePlayNum', 'averageLikeNum', 'fansNum'
      ],
      textkey: [
        'summary', 'cooperationDepartmentNames', 'operateModeName'
      ],
      collectionKey: [
        'relevantUser', 'updateInfo', 'systemAllInfo', 'signDetailStatus', 'contractBroker',
        'otherAccountInfo', 'otherPriceInfo', 'otherOpeatorInfo', 'priceInfo',

        'monthReportPrice', 'nextMonthReportPrice', 'monthNotReportPrice', 'nextMonthNotReportPrice',
        'monthReportPriceCost', 'nextMonthReportPriceCost', 'monthNotReportPriceCost', 'nextMonthNotReportPriceCost',
        'articlesPrice', 'costPrice', 'microTaskCost', 'nowSignStatus', 'journalStatus'
      ],
      noShowKeys: ['accountAllField', 'inSign', 'isNewAccount', 'publicationMonth'],
      dateKey: ['priceUpdateTime']
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    additionalKeys() {
      return ['isVoiceAnchor', 'isFrameOut', 'recommendRank', 'freeAuth', 'otherFreePlatform',
        'hasShopPrice', 'retentionAllowed', 'addBrand', 'allowCar', 'carCommission'];
    },
    propsData() {
      const item = this.column;
      if (item.isDynamicKey) {
        return {
          label: item.name,
          minWidth: '100px'
        };
      }
      return tableFieldProps[item.fieldName] || {};
    },
    isPlatformShow() {
      if (!this.platform) return true;
      const props = this.propsData;
      const platform = Number(this.platform);
      return !props.platform || props.platform.length === 0 || props.platform.includes(platform);
    }
  },
  methods: {
    hasRouteAuth,
    getData(data) {
      const item = this.column;
      if (this.propsData.parentField) {
        if (!data[this.propsData.parentField]) return '';
        return data[this.propsData.parentField][item.fieldName];
      }
      return data[item.fieldName];
    },

    toCooperation(row) {
      const url = this.$router.resolve({
        name: 'supplierManageDetail',
        params: { id: row.supplierId }
      });
      window.open(url.href, '_blank');
    },
    // 展示订单弹窗
    showOrderDialog(item) {
      this.$emit('showOrderDialog', item);
    },
    // 编辑备注
    editRemarkMaskShow(data) {
      this.$emit('editRemarkMaskShow', data);
    },
    editCaseMaskShow(data) {
      this.$emit('editCaseMaskShow', data);
    },
    editInfo(data) {
      const priceTimeAuth = this.hasEditAuth('effective', data); // 报价有效期
      const invoiceInfoAuth = this.hasEditAuth('invoiceInfo', data);
      const sensitiveAuth = this.hasEditAuth('sensitive', data);
      this.$emit('editInfo', data, { priceTimeAuth, invoiceInfoAuth, sensitiveAuth });
    },
    getDynamicKeyContent(item, column) {
      if (item[column.modelKey] && item[column.modelKey].dynamicKey) {
        const cur = item[column.modelKey].dynamicKey.find(i => {
          return i.id.toString() === column.fieldName.toString();
        });
        if (cur) {
          let val = cur.value;
          if (cur.inputType === 1 && cur.options) {
            cur.options.forEach(i => {
              if (i.value === cur.value) val = i.label;
            });
          }
          return val;
        }
      }
      return '';
    },
    /**
     * 权限
     */
    hasEditAuth(type, row) {
      /** 规则
       * 1、如果拥有全向编辑权限，则都可以编辑
       * 2、如果拥有部门全向权限，则自己部门的资源编辑
       * 3、如果拥有普通编辑权限，只有当自己存在于执行人列表时才可以编辑
       */
      return this.hasRouteAuth(`medium:dataEdit:${type}`) && (this.isOperation(row) || this.isDepartmentEdit(row));
    },
    hasCollectionEditAuth(row, fieldName) {
      if (fieldName === 'otherOpeatorInfo') {
        const priceTimeAuth = this.hasEditAuth('effective', row); // 报价有效期
        const invoiceInfoAuth = this.hasEditAuth('invoiceInfo', row);
        const sensitiveAuth = this.hasEditAuth('sensitive', row);

        return priceTimeAuth || invoiceInfoAuth || sensitiveAuth;
      }
      return false;
    },
    isOperation(row) { // 本人是否是执行人
      if (this.userInfo.userName === '管理员') return true;
      const userId = this.userInfo.id;
      const accountOperation = row.accountOperation || [];
      const accountOperationIds = accountOperation.map(i => i.id);
      return accountOperationIds.includes(userId);
    },
    isDepartmentEdit(row) { // 是否拥有全向权限
      if (this.hasRouteAuth('medium:dataEdit:admin')) return true; // 拥有全向权限则全部可以编辑
      if (this.hasRouteAuth('medium:dataEdit:department')) {
      // 如果拥有部门全向编辑，则本部门的资源可以编辑
        const deptName = this.userInfo.deptName;
        if (this.userInfo.userName === '管理员') return true;
        const departmentId = row.attributionMatrix;
        const myDeptNameIds = deptName.map(i => {
          return i.id;
        });
        return myDeptNameIds.includes(departmentId);
      } else {
        return false;
      }
    },
    // 校验对应模块的编辑权限
    fieldEditAuth(column, scope) {
      const specialKeys = ['otherOpeatorInfo', 'remarks', 'cases'];
      if (specialKeys.includes(column.fieldName)) return false;
      if (!column.editModule) {
        return false;
      } else {
        switch (column.editModule) {
          case 'resourceEdit': return hasRouteAuth('medium:dataEdit:createInfo') && scope.row.isEditAuth;
          case 'moreAccountInfoEdit': return hasRouteAuth('medium:dataEdit:moreAccount') && scope.row.isEditAuth;
          case 'journalEdit':return hasRouteAuth('medium:dataEdit:journalInfo') && scope.row.isEditAuth;
          case 'signInfoEdit':return hasRouteAuth('medium:dataEdit:signInfo') && scope.row.isEditAuth;
        }
      }
    },
    editModule(data, editModule = '') {
      this.$emit('toEdit', data, editModule);
    }
  }
};
</script>
<style lang="scss" scoped>

.cursor-pointer {
  cursor: pointer;
  color: #406EFF;
}

.edit-info {
  position: absolute;
  right: 0;
  top: 0;
  width: 0;
  height: 0;
  border-top: 36px solid #EFF3FB;
  border-left: 36px solid transparent;
  visibility: hidden;
  z-index: 3;
  cursor: pointer;
  &::after {
    content: '';
    width: 12px;
    height: 12px;
    position: absolute;
    top: -32px;
    right: 3px;
    background-image: url(../../../../assets/medium/edit.png);
    background-repeat: no-repeat;
    background-size: 100%;
  }
}
</style>
